<?php

namespace app\common\service;

use app\common\service\AbstractService;
use app\systems\model\CommonExportCsvDownloadLogModel;
use app\systems\model\CommonExportCsvTaskLogModel;
use app\systems\model\CommonExportCsvCreateInfoModel;
use app\systems\logic\SystemMqLogic;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Request;
use app\data\util\HttpUtil;
use think\facade\Db;
use app\data\util\CsvHelper;
class CommonExportCsvTaskLogService extends AbstractService
{


    const EXPORT_STATUS_INIT    = 0;//数据待生成
    const EXPORT_STATUS_ING     = 1;//数据生成中
    const EXPORT_STATUS_FAILE   = 2;//数据生成失败
    const EXPORT_STATUS_SYCCESS = 3;//数据生成完成
    const EXPORT_STATUS_PART    = 4;//数据已生成部分
    const EXPORT_STATUS_CANCEL  = 5;//数据取消

    const EXPORT_STATUS_LIST = [
        self::EXPORT_STATUS_INIT    =>'待生成',
        self::EXPORT_STATUS_ING     =>'生成中',
        self::EXPORT_STATUS_FAILE   =>'生成失败',
        self::EXPORT_STATUS_SYCCESS =>'生成完成',
        self::EXPORT_STATUS_PART    =>'已生成部分',
        self::EXPORT_STATUS_CANCEL  =>'已取消',
    ];

    const AMAZON_EXCEPTION_LINK_EXPORT = 128;
    const SHOPIFY_SOURCE_MONTH_EXPORT  = 129;

    const EXPORT_TYPE_MAP = [
        self::AMAZON_EXCEPTION_LINK_EXPORT  => '测试数据导出',
        self::SHOPIFY_SOURCE_MONTH_EXPORT   => '月度业绩数据导出',
    ];

    public $export_csv_task_log_model;
    public $export_csv_create_info_model;
    public $export_csv_download_log_model;
    function __construct($language_file = [])
    {
        parent::__construct($language_file);
        $this->export_csv_task_log_model    = new CommonExportCsvTaskLogModel();
        $this->export_csv_create_info_model = new CommonExportCsvCreateInfoModel();
        $this->export_csv_download_log_model = new CommonExportCsvDownloadLogModel();

    }


    /**
     * @desc   操作导出
     * @author luckyXiong
     * @date   2024-08-07
     */
    public function create_csv_export($taskArr){
        set_time_limit(1800);
        ini_set('memory_limit', '-1');
        $return_data = [];
        try{
            $task['start_time']   = date('Y-m-d H:i:s');
            $task['task_sum']     = ceil($taskArr['rows_sum']/$taskArr['limit']);
            $task['created_unix'] = time();
            $taskLog = array_merge($task,$taskArr);
            $model   = $this->export_csv_task_log_model;
            $model->save($taskLog);
            $id = $model->id;
            if($id>0){
                //生成task
                $save_csv_path = FCPATH .UPLOAD_FILE_DOMAIN_NAME.'/excel/' . date('Ym/d/');
                if (!is_dir($save_csv_path)) {
                    mkdir($save_csv_path,0777 ,true);
                }
                $num = ceil($taskLog['rows_sum']/$taskArr['limit']);
                for($i=0;$i<$num;$i++){
                    $info = [];
                    $info['export_csv_task_id'] = $id;
                    $info['task_done_no'] = $i+1;
                    $info['create_time'] = date('Y-m-d H:i:s');
                    $info['status'] = 0;

                    $info = [
                        'export_csv_task_id'=>$id,
                        'task_done_no'      =>$i+1,
                        'create_time'       =>date('Y-m-d H:i:s'),
                        'status'            =>0,
                    ];
                    $res_id = Db::name('common_export_csv_create_info')->insertGetId($info);
                    if($res_id){
                        $this->do_push_queue_from_export($res_id,'',$taskArr['data_type']);
                    }
                }
                $return_data['status'] = 2;
                $return_data['msg'] = "数据超过".$taskArr['limit']."条,异步下载中，请前往【系统管理/系统导出管理】页面下载";
            }else{

                throw new \Exception('创建任务失败');
            }

        }catch (\Exception $e){
            $return_data['status'] = 0;
            $return_data['msg'] = $e->getMessage();

        }

        return $return_data;

    }

    /**
     * @Notes:推送队列
     * @author luckyXiong
     * @date   2024-08-07
     * @param $export_id
     * @param $platform_code
     * @param $data_type
     */
    public function do_push_queue_from_export($export_id,$platform_code,$data_type=''){
        $pushmessage['type']          = MqTaskPushLogic::TYPE_COMMON_SYSTEM_EXPORT;
        $pushmessage['id']            = $export_id;
        $pushmessage['platform_code'] = $platform_code;
        $pushmessage['data_type']     = $data_type;
        //推送到队列
        MqTaskPushLogic::common_system_export_task_push($pushmessage);
    }


    /**
     * @Notes:下载
     * @Author: TCP
     * @Date: 2021/3/25
     * @Time: 19:01
     * @param $param
     * @return array
     */
    public function down_csv_export($param){
        //获取下级用户
        $return_data = [];
        try{
            $csvInfo = $this->export_csv_task_log_model->where(['id'=>$param['export_id']])->find();
            $csvInfo = objectToArray($csvInfo);
            if($csvInfo['status']!=3){
                if($csvInfo['status']!=4||($csvInfo['status']==4&&($csvInfo['task_sum']!=$csvInfo['done_task']))){
                    die(json_encode(['status' => 0, 'msg' => '数据未生成完，暂不能下载']));
                }
            }

           if($csvInfo['path']){
                $return_data['status'] = '1';
                $return_data['msg'] = '下载成功';
                $return_data['export_name'] = $csvInfo['task_name'];
                $return_data['export_url'] = FILE_DOWNLOAD_DOMAIN_NAME.$csvInfo['path'];
            }else{
                //组合下载
                $return_data = $this->composeCreateCsv($csvInfo['id']);
                if($return_data['status']==2){
                    throw new \RuntimeException($return_data['msg']);
                }
            }
            //添加下载log
            $export_csv_download_log_model = $this->export_csv_download_log_model;
            $export_csv_download_log_model->export_csv_task_log_id = $csvInfo['id'];
            $export_csv_download_log_model->operate_time = date('Y-m-d H:i:s');
            $export_csv_download_log_model->operate_work_num = $param['create_work_num']??'';
            $export_csv_download_log_model->save();
        }catch (\Exception $e){
            $return_data['status'] = '0';
            $return_data['msg'] = $e->getMessage();
        }
        return $return_data;

    }


    /**
     * @desc   测试导出数据
     * @author luckyXiong
     * @date   2024-08-08
     */
    public function operate_export_follow_data($data){
        list($model,$params,$data_type,$services,$services_patch) = $data;
        $export_type = isset($params['export_type'])?$params['export_type']:"addTask";
        unset($params['export_type']);
        try{
            if($export_type=='addTask'){

                //创建任务
                $addition_filed= !empty($params['filed'])?$params['filed']:"";
                $fun = 'export_set_heading';

                if(!method_exists($services, $fun)) {
                    throw new \Exception('请先配置表头方法'.$fun);
                }
                $exportHeading = $services->$fun($addition_filed);

                $addition = !empty($addition_filed)?json_encode($addition_filed):"";
                if(isset($params['page'])){
                    unset($params['page']);
                }
                $currentUri = Request::url();
                $params['download_url'] = isset($params['download_url'])?$params['download_url']: $currentUri;

                # 兼容一个服务多个下载的问题
                $pams = '?export_type=downLoad';
                $download_url = $params['download_url'] . $pams;

                $create_work_num = $params['create_work_num'];
                unset($params['download_url']);
                $action_name = isset($params['action_name'])?$params['action_name']:"get_follow_list_export";

                //获取对应条件的总数
                $limit_num            = isset($params['limit'])?$params['limit']:1000;
                $export_platform_code = 'SHOPIFY';
                $total_value          = $model->pageList($params);
                $total_num            = $total_value['total']??0;
                if ($total_num == 0){
                    throw new \Exception('暂无数据，不支持导出');
                }else{
                    $download_url     = $download_url."&platform_code=".$export_platform_code;
                    $taskArr = [
                        'platform_code'   =>$export_platform_code,
                        'csv_header'      => json_encode($exportHeading),
                        'return_url'      => $download_url,
                        'task_name'       => $this::EXPORT_TYPE_MAP[$data_type] .'-'. date('Y-m-d-H-i-s', time()).'-'. $params['create_work_num'],
                        'data_type'       => $data_type,
                        'service_name'    => $services_patch,
                        'action_name'     => $action_name,//Service层中对应处理导出数据的方法
                        'addition'        => $addition,//其他附加条件
                        'custom'          => json_encode($params),
                        'rows_sum'        => empty($total_num) ? 0 : $total_num,
                        'limit'           => $limit_num,
                        'created_work_no' => $create_work_num,
                    ];
                    $return_data =  $this->create_csv_export($taskArr);
                }
            }else{
                //下载
                $return_data = $this->down_csv_export($params);
            }

        }catch (\Exception $e){
            $return_data['status'] = 0;
            $return_data['msg'] = $e->getMessage();
        }
        return $return_data;

    }


    /**
     * @Notes:组合生成csv文件
     * @Author: TCP
     * @Date: 2021/1/5
     * @Time: 15:04
     * @param $export_id任务id
     * @param $task_done_no
     */
    public function composeCreateCsv($export_id='', $task_done_no=0)
    {
        set_time_limit(1800);
        ini_set('memory_limit', '-1');
        $task = $this->export_csv_task_log_model->where('id',$export_id)->find();
        $task->updated_unix = time();  #记录任务执行时间
        if ($task->status == self::EXPORT_STATUS_INIT) {
            $task->status  = self::EXPORT_STATUS_ING;
        }
        $task->save();
        $condition                       = [];
        $condition['export_csv_task_id'] = $export_id;
        if($task_done_no){
            $condition['task_done_no']   = $task_done_no;
        }
        try{
            $csvInfo = $this->export_csv_create_info_model->getOneResultArray($condition);
            if(!$csvInfo){
                $resdata = $this->composeCsv($export_id);
            }else{
            $exportService =   new $task->service_name();
            $function = $task->action_name;
            $func = empty($function)?self::$func:$function;
            $task_name = $task->task_name.'-'.$csvInfo['task_done_no'];
            $custom_param = json_decode($task->custom, true);
            #20211230 zhangji 追加创建人为参数，异步导出权限控制会用到
            $custom_param['created_work_no'] = $task->created_work_no;
            $custom_param['limit'] = $task->limit;
            $custom_param['page'] = $csvInfo['task_done_no'];
            $exportData = $exportService->$func($custom_param,json_decode($task->addition, true));//限制条件，limit限制数默认1w，偏移量默认0
            $csv_header = [];
            if($csvInfo['task_done_no']==1){
                $csv_header = json_decode($task->csv_header,true);
            }
            $res =self::createCSV($exportData,$csv_header, $task_name, false, UPLOAD_FILE_DOMAIN_NAME."/excel/");
            $updateArr = [];
            if (isset($res['status']) && $res['status'] == '200') {
                $updateArr['end_time'] =  date('Y-m-d H:i:s');
                $updateArr['status']   = 2;
                $updateArr['info']     = '/'.$res['data'];
                $details_res = $this->export_csv_create_info_model->where(['id'=>$csvInfo['id']])->update($updateArr);
                if($details_res){
                    $rows = $this->export_csv_create_info_model->getRowResultArray(['export_csv_task_id'=>$export_id,'status'=>2]);
                    $task->done_task =$rows['num'];
                    if($rows['num']==$task->task_sum){
                        $task->done_sum = $task->rows_sum;
                    }else{
                        $row_num = $rows['num']-1;
                        $task->done_sum = ($row_num*$task->limit)+count($exportData);
                    }

                    $task->end_time = date('Y-m-d H:i:s');
                    $task->status = self::EXPORT_STATUS_PART;
                    $task->save();
                    //合并csv
                    $resdata = $this->composeCsv($export_id);
                }

            } else {
                $resdata['status'] = '2';
                $resdata['msg']    = '生成csv文件错误';
                $this->export_csv_create_info_model->where(['id'=>$csvInfo['id']])->update([
                    'end_time'=>date('Y-m-d H:i:s'),
                    'status'  =>3,
                    'info'    =>$res['data']??'',
                ]);
            }
            }
        }catch (\Exception $e){
            $resdata['status'] = '2';
            $resdata['msg'] = !empty($e->getMessage())?$e->getMessage():'执行失败';
        }
        return $resdata;
    }


    /**
     * @desc   csv消费方法
     * @author luckyXiong
     * @date   2024-08-12
     */
    public function createCsvConsumer($params)
    {
        $export_id    = $params['export_csv_task_id']??'';
        $task_done_no = $params['task_done_no']??'';
        $task = $this->export_csv_task_log_model->where('id',$export_id)->find();
        $condition                       = [];
        $condition['export_csv_task_id'] = $export_id;
        if($task_done_no){
            $condition['task_done_no']   = $task_done_no;
        }
        $csvInfo = $this->export_csv_create_info_model->getOneResultArray($condition);
        if(!$csvInfo){
            $this->composeCsv($export_id);
        }else{
            $exportService =   new $task->service_name();
            $function = $task->action_name;
            $func = empty($function)?self::$func:$function;
            $task_name = $task->task_name.'-'.$csvInfo['task_done_no'];
            $custom_param = json_decode($task->custom, true);
            #20211230 zhangji 追加创建人为参数，异步导出权限控制会用到
            $custom_param['created_work_no'] = $task->created_work_no;
            $custom_param['limit'] = $task->limit;
            $custom_param['page'] = $csvInfo['task_done_no'];
            $exportData = $exportService->$func($custom_param,json_decode($task->addition, true));//限制条件，limit限制数默认1w，偏移量默认0
            $csv_header = [];
            if($csvInfo['task_done_no']==1){
                $csv_header = json_decode($task->csv_header,true);
            }
            $res =self::createCSV($exportData,$csv_header, $task_name, false, UPLOAD_FILE_DOMAIN_NAME."/excel/");
            $updateArr = [];
            if (isset($res['status']) && $res['status'] == '200') {
                $updateArr['end_time'] =  date('Y-m-d H:i:s');
                $updateArr['status']   =  2;
                $updateArr['info']     =  '/'.$res['data'];
                $details_res = $this->export_csv_create_info_model->where(['id'=>$csvInfo['id']])->update($updateArr);
                if($details_res){
                    $rows = $this->export_csv_create_info_model->getRowResultArray(['export_csv_task_id'=>$export_id,'status'=>2]);
                    $task->done_task =$rows['num'];
                    if($rows['num']==$task->task_sum){
                        $task->done_sum = $task->rows_sum;
                    }else{
                        $row_num = $rows['num']-1;
                        $task->done_sum = ($row_num*$task->limit)+count($exportData);
                    }
                    $task->end_time = date('Y-m-d H:i:s');
                    $task->status = self::EXPORT_STATUS_PART;
                    $task->save();
                    //合并csv
                    $resdata = $this->composeCsv($export_id);
                }

            } else {
                $resdata['status'] = '2';
                $resdata['msg']    = '生成csv文件错误';
                $this->export_csv_create_info_model->where(['id'=>$csvInfo['id']])->update([
                    'end_time'=>date('Y-m-d H:i:s'),
                    'status'  =>3,
                    'info'    =>$res['data']??'',
                ]);
            }
        }
        return $resdata;
    }






    /**
     * @desc   合并数据
     * @author luckyXiong
     * @date   2024-08-08
     */
    public function composeCsv($export_id){
        $task = $this->export_csv_task_log_model->where(['id'=>$export_id])->find();
        if($task->task_sum==$task->done_task&&empty($task->path)){
            $condition['status']=2;
            $condition['export_csv_task_id']=$export_id;
            $csvTaskInfo =  $this->export_csv_create_info_model->getAllResultArray2($condition);
            $fileData = array();
            foreach($csvTaskInfo as $val){
                if ( strpos(PHP_OS,"Linux")===false){
                    $val['info'] = iconv('UTF-8', 'GBK//IGNORE', $val['info']);
                }
                if(file_exists('./'.$val['info'])){
                    $fileData[] = $val['info'];
                }
            }
            if(!empty($fileData)){
                    $filenames = $task->task_name.'merge'.time() ;
                    $filePath  = CsvHelper::mergeCSV($fileData,$filenames);
                    if(!empty($filePath)){
                        $return_data['status'] = '1';
                        $return_data['msg'] = '合并成功';
                        $return_data['export_url'] = FILE_DOWNLOAD_DOMAIN_NAME.$filePath;
                        $return_data['export_name'] = $task->task_name;

                        //保存路径
                        $task->path = $filePath;
                        $task->status = self::EXPORT_STATUS_SYCCESS;
                        $task->end_time = date('Y-m-d H:i:s');
                        $task->save();
                    }else{
                        $return_data['status'] = '2';
                        $return_data['msg'] = 'csv合并失败';

                    }
            }else{
                $return_data['status'] = '2';
                $return_data['msg'] = 'csv合并失败';
            }

        }elseif ($task->task_sum>$task->done_task){
            $return_data['status'] = '2';
            $return_data['msg'] = $task->task_name.'需要继续合并';
        }else{
            $return_data['status'] = '2';
            $return_data['msg'] = $task->task_name.'无需合并';
        }
        return $return_data;
    }


    /**
     * @Notes:合并为zip
     * @Author: TCP
     * @Date: 2021/1/20
     * @Time: 17:47
     * @param $fileData
     * @param $task
     * @return string
     */
    public function mergeZIP($fileData,$task){
        $merge_num = ceil($task->rows_sum/1000000);
        $merge_num = $merge_num>2?$merge_num:2;
        $num = ceil(count($fileData)/$merge_num);//只分2个excel
        $arr = array_chunk($fileData, $num,true);
        $folder = "upload/yibai_sale_center/excel/".date('Ym/d/');

        $path = FCPATH .$folder;
        if(!is_dir($path)) mkdir($path, 0777, true);
        if (is_dir($path)) {
            if ( strpos(PHP_OS,"Linux")!==false){
                touch($task->task_name);  //这个中文不乱码
            }else{
                $task->task_name = iconv('UTF-8', 'GBK//IGNORE', $task->task_name);
            }
            @mkdir($path . 'zip/' . $task->task_name, 0777, true);
        }

        for ($i = 0; $i < count($arr); $i++) {
            $tmpname = '/' . $task->id . '_zip_' . $i . '.csv';
            $n = 0;
            foreach ($arr[$i] as $file) {
                $file = FCPATH . $file;
                if(file_exists($file)){
                    //这里直接移动文件到目标下载文件，而不需要写入到文件
                    if ($n == 0) {
                        copy($file ,$path . 'zip/' . $task->task_name . $tmpname);
                    } else {
                        file_put_contents($path . 'zip/' . $task->task_name . $tmpname ,file_get_contents($file) ,FILE_APPEND);
                    }
                    $n++;
                }
            }
        }
        $zipName = $path . $task->task_name . '.zip';
        $zip = new \ZipArchive();
        $fromPath = $path . 'zip/' . $task->task_name;
        if ($zip->open($zipName, \ZIPARCHIVE::CREATE)) {
            self::createZip(opendir($fromPath), $zip, $fromPath);
            $zip->close();
        }
        if ( strpos(PHP_OS,"Linux")===false){
            $task->task_name =  iconv('GBK', 'UTF-8//IGNORE', $task->task_name);
        }
        $zname = '/'.$folder . $task->task_name . '.zip';
        self::deldirfile($path . 'zip/' . $task->task_name);

        return $zname;
    }


    /**
     * @desc   生成CSV数据
     * @author luckyXiong
     * @date   2024-08-10
     */
    public function createCSV($rows, $header=[], $filename=null, $is_download=false, $save_path = '/storage/excel/')
    {

        if ($is_download) {
            return CsvHelper::exportCSV($rows, $header, $filename);
        } else {
            $unique_name = date('YmdHis') . mt_rand(1000, 9999);
            if (!empty($filename)) {
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                if ($ext) $ext = '.' . $ext;
                $unique_name = basename($filename, $ext) . '_' . $unique_name . $ext;
            }

            $save_path = $save_path . date('Ym/d/');
            if (!is_dir($save_path)) mkdir($save_path, 0777, true);
            $filename = $save_path . $unique_name;
            $result = CsvHelper::createCSV($rows, $header, $filename);
            if (isset($result['data'])) $result['data'] = str_replace(APPPATH, '', $result['data']);
            return $result;
        }
    }









    /**
     * @Notes:生成完ZIP后删除文件
     * @Author: TCP
     * @Date: 2021/1/20
     * @Time: 17:47
     * @param $dir
     */
    public static function deldirfile($dir)
    {
        // 打开指定目录
        if ($handle = @opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if (($file == ".") || ($file == "..")) {
                    continue;
                }
                if (is_dir($dir . '/' . $file)) {
                    // 递归
                    self::deldirfile($dir . '/' . $file);
                } else {
                    unlink($dir . '/' . $file); // 删除文件
                }
            }
            @closedir($handle);
            rmdir($dir);
        }
    }


    /**
     * @Notes:生成zip
     * @Author: TCP
     * @Date: 2021/1/20
     * @Time: 17:47
     * @param $openFile
     * @param $zip
     * @param $from
     * @param string $newname
     */
    public static  function createZip($openFile,$zip,$from,$newname =''){

        while (($file = readdir($openFile)) != false) {
            if ($file == "." || $file == "..") {
                continue;
            }
            $sourceTemp = $from . '/' . $file;
            $newTemp = $newname == '' ? $file : $newname . '/' . $file;
            if (is_dir($sourceTemp)) {
                $zip->addEmptyDir($newTemp);
                self::createZip(opendir($sourceTemp), $zip, $sourceTemp, $newTemp);
            }
            if (is_file($sourceTemp)) {
                $zip->addFile($sourceTemp, $newTemp);
            }

        }
    }


    /**
     * @Notes:获取各个平台的services
     * @Author: TCP
     * @Date: 2021/5/21
     * @Time: 9:10
     * @param $platform
     * @return string
     */
    public  function get_platform_export_services($platform) {
        if(empty($platform) || $platform === 'demo'){
            $platform = 'common';
        }

        $platform = $this->get_platform_obj($platform, 'export_csv_create_info_service');

        return  $platform;
    }



    /**
     * @Notes:获取下载日志
     * @Author: TCP
     * @Date: 2021/3/26
     * @Time: 19:55
     * @param $param
     */
    public function get_export_log($param){
        $renderData = [];
        try{
            if(empty($param['id'])) {
                throw new \RuntimeException('请先选择需要导出id');
            }
            $export_csv_download_log_model = Common_export_csv_download_log_model::staticModel();
            $condition['export_csv_task_log_id'] = $param['id'];
            $byConditiion['limit'] = 50;
            $byConditiion['order_by'] = 'operate_time desc';
            $logList = $export_csv_download_log_model->getAllResultArray($condition,'id,operate_time,operate_work_num',$byConditiion);
            //文件名
            $fileName = Common_export_csv_task_log_model::staticModel()->getRowResultArray(['id'=>$param['id']],'task_name');

            if(!empty($logList)){
                foreach($logList  as &$data){
                    $work_no_map = System_oa_user_service::staticModel()->get_oa_user_user_number_pairs(['userNumber' => $data['operate_work_num']]);
                    $work_no_map && $data['operate_work_num'] =  array_shift($work_no_map);
                    $data['file_name'] = $fileName['task_name'];
                }
            }

            $info['data']  = $logList ? $logList :[];
            $info['title'] = ['file_name'=>'操作事项','operate_work_num'=>'操作人','operate_time'=>'操作时间'];
            $this->triggerSuccess('操作成功',$info);
        }catch (\Exception $e){
            $this->triggerError($e->getMessage(), null);
        }
        return $this->triggerReturnMessage();
    }

    /**
     * @Notes:搜索
     * @Author: TCP
     * @Date: 2021/5/24
     * @Time: 16:05
     */
    public function common_system_export_filter(){
        $filter = Common_system_export_filter::static_model()->filterOption();
        $this->triggerSuccess('返回查询条件',$filter);
        return $this->triggerReturnMessage();
    }


    /**
     * @Notes:获取列表数据
     * @Author: TCP
     * @Date: 2021/5/24
     * @Time: 17:07
     * @param $params
     */
    public function page_list_service($params){
        #20211203增加权限(当前用户只能看自己的数据)
        ##只能看到自己导出数据，上级能看下级导出列表数据
        $staffCode = get_instance()->user->staffCode;
        #获取当前登录账号的所有下级
        $list = System_oa_user_service::staticModel()->get_oa_user_api(['userNumber' => $staffCode]);
        $staffCodeArr = [$staffCode];
        if($list['data_list']){
            $userNumberArr = array_column($list['data_list'],'userNumber');
            $staffCodeArr = array_unique(array_merge($userNumberArr,$staffCodeArr));
        }
        $params['created_work_no'] = $staffCodeArr;

        $model = Common_export_csv_task_log_model::staticModel();
        $model->page_list_service_select();
        //  $model->page_list_service_join();
        $model->page_list_service_condition();
        $dataList = $model->pageList($params,true,false);
        $dataList['title'] = Common_system_export_filter::static_model()->attribute_labels();
        $dataList['data'] = $this->page_list_service_data($dataList['data']);
        $this->triggerSuccess('返回列表',$dataList);
        return $this->triggerReturnMessage();
    }

    /**
     * @Notes:列表数据二次处理
     * @Author: TCP
     * @Date: 2021/5/24
     * @Time: 19:13
     * @param $list
     * @return mixed
     */
    public function page_list_service_data(&$list){

        if ($list){
            $importStatus= self::EXPORT_STATUS_LIST;
            $importType= self::EXPORT_TYPE_MAP;
           // $platform = Common_system_import_service::staticModel()->get_platform();
            $export_csv_download_log_model = Common_export_csv_download_log_model::staticModel();
            foreach ($list as &$data) {
                $data['status'] = $importStatus[$data['status']];
                $data['data_type'] = $importType[$data['data_type']];
                $work_no_map = System_oa_user_service::staticModel()->get_oa_user_user_number_pairs(['userNumber' => $data['created_work_no']]);
                $work_no_map && $data['created_work_no'] = array_shift($work_no_map);
                $down_num = $export_csv_download_log_model->getRowResultArray(['export_csv_task_log_id', $data['id']], 'count(id) as total_num');
                $data['down_num'] = empty($down_num['total_num']) ? 0 : $down_num['total_num'];

                #$data['platform_code'] = isset($platform[$data['platform_code']]) ? $platform[$data['platform_code']] : $data['platform_code'];
                $data['return_url'] = $data['return_url'] .'&export_id=' . $data['id'];


                $data['created_unix'] = empty($data['created_unix']) ? '' : date('Y-m-d H:i:s', $data['created_unix']);
            }

        }

        return $list;
    }


    /**
     * @Notes:定时跑处理导出接口
     * @Author: TCP
     * @Date: 2021/5/25
     * @Time: 14:48
     */
    public function do_export_detail_task($params){
        set_time_limit(0);
        $platform_code = isset($params['platform_code'])?$params['platform_code']:"common";
        $redis = \Rediss::getInstance();
        $key = $platform_code.'_run_export_detail_task_20210525new';
        $prefixKey = $redis->getPrefix().$key;

        $system_export_detail_service = $this->get_platform_export_services($platform_code);
        if(empty($system_export_detail_service)){
            return ['status' => 0 ,'error_msg' => '请先传入正确平台platform_code'];
        }

        $detail_model = $system_export_detail_service->export_csv_create_info_model;

        if(!empty($params['run']) || !empty($params['id'])){
            $startTime = time();

            while (time() - $startTime < 550) {
                if (isset($params['id'])) {
                    $id = $params['id'];

                } else {
                    $id = $redis->rPop($prefixKey);
                }
                if (!$id) {
                    $resultMsg[$id] = 'id 不可为空，任务已执行完成';
                    break;
                }
                try {
                    //操作对应的数据
                    $resultMsg[$id] = $system_export_detail_service->createCsvInfo($id);

                } catch (\Exception $e) {
                    $resultMsg[] = $e->getMessage();
                }
                if (isset($params['id'])) break;
            }

            return $resultMsg;

        }

        //获取各平台对应的导入详情未执行数据
        $data = $detail_model->getAllResultArray(['status'=>0],'id',['limit' => 30000]);

        if (empty($data)) {
            $resultMsg['message'] = '数据已更新完成，查询无数据';
            return $resultMsg;
        }
        $id = array_column($data ,'id');
        $redisTaskId = $redis->queueRange($key);
        $id = array_diff($id ,$redisTaskId);
        $idChunk = array_chunk($id ,200);

        foreach ($idChunk as $idChunkItem) {
            $redis->rPush($prefixKey  ,$idChunkItem);
        }
        $len = $redis->queueLen($key);
        $socket = ceil($len / 100) ;
        $socket = $socket > 30 ? 30 : $socket;
        while ($socket) {
            run_thread_socket('/cron/common_system_export_cron/run_export_detail_task?platform_code='.$platform_code.'&run='.$socket);
            $resultMsg[] = '/cron/common_system_export_cron/run_export_detail_task?platform_code='.$platform_code.'&run='.$socket;
            $socket--;
        }

        return $resultMsg;
    }

    /**
     * @Notes:修改状态
     * @Author: TCP
     * @Date: 2021/5/25
     * @Time: 15:49
     * @return array
     */
    public function update_detail_status()
    {
        try{
            $updated_unix = time() - 3600;
            $taskAll = $this->export_csv_task_log_model->getAllResultArray([['_in', 'status',['0','1','4']], 'updated_unix <'=>$updated_unix], 'id, created_unix, platform_code');
            $res  = [];
            $time = time();
            foreach($taskAll as $k=>$v)
            {
                if(time() - $time >= 720) break;
                $upDa = ['updated_unix'=>$time];

                #超过1天的 + 未创建任务的 标记失败
                if($time - $v['created_unix'] >= 86400 || $this->get_queue_name($v['platform_code']))
                {
                    $system_export_detail_service = $this->get_platform_export_services($v['platform_code']);
                    $result = $system_export_detail_service->update_detail_status($v['platform_code'], $v['id']);
                    $res[$v['platform_code']] = $result;

                    $upDa['status'] = ($result['status'] === '1') ? 1 : 2;  # 2数据生成失败
                }
                $this->export_csv_task_log_model->updateAll($upDa, ['id'=>$v['id']]);
            }

        }catch (\Throwable $e){
            $res = $e->getMessage();
        }
        return $res;
    }



    /**
     * 检查队列里面是否有数据
     * @param string $platform_code
     * @return bool
     * @throws \AMQPChannelException
     * @throws \AMQPQueueException
     */
    private function get_queue_name($platform_code=''){
        $queue_name=Mq_task_push_service::get_system_export_task_bind_key($platform_code,'sale_center_system_export_task');
        //获取队列
        $mq_config=Mq_group_service::get_mq_group_by_queue($queue_name);
        $rabbitQq = new \Rabbitmq($mq_config['mq_config']);
        $len = $rabbitQq->mq_get_queue_num($mq_config['queue_name']);
        if ($len == 0)return true;
        return false;
    }


    /**
     * @Notes:消费导出队列
     * @Author: TCP
     * @Date: 2021/5/25
     * @Time: 17:29
     * @param $message
     */
    public function consume_center_system_export_queue($message){
        try {
            $system_import_detail_service = (new CommonExportInfoDetailService());
            return $system_import_detail_service->createCsvInfo($message);
        } catch (\Throwable $e) {
            return $e->getMessage();
        }
        return true;

    }



    /**
     * 查询导出任务记录单条信息
     * @param array $condition
     * @param string $field
     * @return array|\Model|null
     * @throws \Exception
     */
    public function get_common_export_csv_task_log($condition = [], $field ='*')
    {
        if(empty($condition)) {
            return [];
        }
        return Common_export_csv_task_log_model::staticModel()->findOne($condition, false, $field);
    }



}
